const validators = {
  phone: /^1[3456789]\d{9}$/,
  pwd: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/,
  //pwd:/^(?=.*[a-zA-Z\d])[!-~]{8,16}$/ 特殊字符+数字+字母
  // pwd: /^((?=.*[0-9a-zA-Z])(?=.[\`\~\!\@\#\$\%\^\&\*\(\)\_\+\-\=\{\}\|\[\]\:\;\'\<\>\?\,\.]*)).{8,16}$/,
  // pwd2:/^[^ ]+$/,
  // email: /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/
  email: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
}

const toast = function (tip) {
  wx.showToast({
    title: tip || '网络连接失败',
    icon: 'none',
    duration: 2000
  });
}

const formatTime = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
}

const urlEncode = function (str) {
  return escape(str).replace(/\+/g, '%2B');
}
const formatQueryTime = timestamp => {
  if (!timestamp)
    return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}-${month}-${day}`;
}
/**
 *
 * @param fn {Function}   实际要执行的函数
 * @param delay {Number}  延迟时间，单位是毫秒（ms）
 *
 * @return {Function}     返回一个“防反跳”了的函数
 */

let debounce_timer;
const debounce = function (fn, delay) {
  // 定时器，用来 setTimeout
  // 返回一个函数，这个函数会在一个时间区间结束后的 delay 毫秒时执行 fn 函数
  return function () {
    const context = this;
    const args = arguments;
    // 每次这个返回的函数被调用，就清除定时器，以保证不执行 fn
    clearTimeout(debounce_timer);
    // 当返回的函数被最后一次调用后（也就是用户停止了某个连续的操作），
    // 再过 delay 毫秒就执行 fn
    debounce_timer = setTimeout(function () {
      fn.apply(context, args)
    }, delay);
  }
}

let last_time = null;
const timeGap = 600;

const preventMoreClick = function (context, fn) {
  let now_time = new Date().getTime();
  if (!last_time || now_time - last_time > timeGap) {
    fn.call(context);
    last_time = now_time;
  }
}

const deepClone = function (obj) {
  let newObj = obj instanceof Array ? [] : {};
  for (let i in obj) {
    newObj[i] = (typeof obj[i] == 'object' && obj[i] !== null) ?
      deepClone(obj[i]) : obj[i];
  }
  return newObj;
}

module.exports = {
  validators,
  toast,
  formatTime,
  formatNumber,
  urlEncode,
  debounce,
  preventMoreClick,
  deepClone,
  formatQueryTime

}